package com.google.code.chaotic.storedprocs;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.postgresql.pljava.ResultSetHandle;

//

public class OriginDensitiesRSHandle implements ResultSetHandle {

	public static final double DEFAULT_DENSITY_RADIUS = 2000;

	public static ResultSetHandle list() throws SQLException {
		return list(DEFAULT_DENSITY_RADIUS);
	}

	public static ResultSetHandle list(double raduis) throws SQLException {
		return new OriginDensitiesRSHandle(raduis);
	}

	//

	private OriginDensitiesRSHandle(double distance) throws SQLException {
		Connection conn = DriverManager
				.getConnection("jdbc:default:connection");
		String //
		sqlStmt = " SELECT id, ST_AsText(orig_gis),"
				+ "		(SELECT count(id) FROM vw_origins AS v2"
				+ "		 WHERE ST_DWithin(v1.orig_gis, v2.orig_gis, ?) ) AS density"
				+ " FROM vw_origins AS v1" // 
				+ " ORDER BY density DESC";

		stmt = conn.prepareStatement(sqlStmt);
		stmt.setDouble(1, distance);
	}

	private PreparedStatement stmt;

	public ResultSet getResultSet() throws SQLException {
		ResultSet rs = stmt.executeQuery();
		return rs;
	}

	public void close() throws SQLException {
		stmt.close();
	}

}
